<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF在线修改工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --success-color: #4cc9f0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fb;
            color: var(--dark-color);
        }
        
        .navbar {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 20px;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            background-color: white;
            border-bottom: 1px solid #eaeaea;
            font-weight: 600;
            padding: 15px 20px;
            border-radius: 10px 10px 0 0 !important;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background-color: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .pdf-preview-wrapper {
            position: relative;
            width: 100%;
            min-height: 600px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background-color: #f9f9f9;
            overflow: auto;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding: 20px;
        }
        
        .pdf-container {
            position: relative;
            display: inline-block;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            background: white;
            cursor: crosshair;
        }
        
        .page-canvas {
            display: block;
            max-width: 100%;
            height: auto;
        }
        
        .selection-area {
            position: absolute;
            border: 2px solid var(--primary-color);
            background-color: rgba(67, 97, 238, 0.1);
            pointer-events: none;
            z-index: 10;
        }
        
        .selection-handle {
            position: absolute;
            width: 8px;
            height: 8px;
            background-color: var(--primary-color);
            border: 1px solid white;
            border-radius: 50%;
            pointer-events: all;
            z-index: 20;
        }
        
        .selection-handle.nw { top: -4px; left: -4px; cursor: nw-resize; }
        .selection-handle.ne { top: -4px; right: -4px; cursor: ne-resize; }
        .selection-handle.sw { bottom: -4px; left: -4px; cursor: sw-resize; }
        .selection-handle.se { bottom: -4px; right: -4px; cursor: se-resize; }
        .selection-handle.n { top: -4px; left: 50%; transform: translateX(-50%); cursor: n-resize; }
        .selection-handle.s { bottom: -4px; left: 50%; transform: translateX(-50%); cursor: s-resize; }
        .selection-handle.w { left: -4px; top: 50%; transform: translateY(-50%); cursor: w-resize; }
        .selection-handle.e { right: -4px; top: 50%; transform: translateY(-50%); cursor: e-resize; }
        
        .coordinates-display {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.8rem;
            z-index: 30;
        }
        
        .modification-item {
            border-left: 3px solid var(--primary-color);
            padding: 10px 15px;
            margin-bottom: 10px;
            background-color: #f8f9ff;
            border-radius: 0 5px 5px 0;
        }
        
        .progress-bar {
            background-color: var(--success-color);
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
            position: relative;
        }
        
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #e0e0e0;
            z-index: 1;
        }
        
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 5px;
            color: white;
        }
        
        .step.active .step-number {
            background-color: var(--primary-color);
        }
        
        .step.completed .step-number {
            background-color: var(--success-color);
        }
        
        .modification-controls {
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
        }
        
        .file-upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 40px 20px;
            text-align: center;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .file-upload-area:hover, .file-upload-area.dragover {
            border-color: var(--primary-color);
            background-color: #f0f4ff;
        }
        
        .file-info {
            background-color: #e8f4fe;
            border-radius: 6px;
            padding: 10px 15px;
            margin-top: 15px;
        }
        
        footer {
            background-color: var(--dark-color);
            color: white;
            padding: 30px 0;
            margin-top: 50px;
        }
        
        .operation-log {
            max-height: 200px;
            overflow-y: auto;
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 10px;
            font-size: 0.9rem;
        }
        
        .log-entry {
            padding: 5px 0;
            border-bottom: 1px solid #eaeaea;
        }
        
        .log-time {
            color: #6c757d;
            font-size: 0.8rem;
        }
        
        .page-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .zoom-controls {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .alert-area {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
            min-width: 300px;
        }
    </style>
</head>
<body>
    <!-- 加载遮罩 -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
        <div class="text-white mt-3" id="loadingText">处理中...</div>
    </div>

    <!-- 消息提示区域 -->
    <div class="alert-area" id="alertArea"></div>

    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-file-pdf me-2"></i>PDF在线修改工具
            </a>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="container my-5">
        <div class="row">
            <div class="col-12">
                <h1 class="text-center mb-4">PDF在线修改工具</h1>
                <p class="text-center text-muted mb-5">上传您的PDF文件，选择需要修改的区域，轻松完成内容修改</p>
                
                <!-- 步骤指示器 -->
                <div class="step-indicator">
                    <div class="step active">
                        <div class="step-number">1</div>
                        <div>上传PDF</div>
                    </div>
                    <div class="step">
                        <div class="step-number">2</div>
                        <div>选择修改区域</div>
                    </div>
                    <div class="step">
                        <div class="step-number">3</div>
                        <div>设置修改内容</div>
                    </div>
                    <div class="step">
                        <div class="step-number">4</div>
                        <div>下载修改后文件</div>
                    </div>
                </div>
                
                <!-- 文件上传区域 -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-cloud-upload-alt me-2"></i>上传PDF文件
                    </div>
                    <div class="card-body">
                        <div class="file-upload-area" id="fileUploadArea">
                            <i class="fas fa-file-pdf fa-3x mb-3 text-primary"></i>
                            <h5>拖放PDF文件到此处或点击上传</h5>
                            <p class="text-muted">支持最大100MB的PDF文件</p>
                            <input type="file" id="fileInput" accept=".pdf" style="display: none;">
                            <button class="btn btn-primary mt-3" id="uploadButton">选择文件</button>
                        </div>
                        <div class="file-info d-none" id="fileInfo">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <i class="fas fa-file-pdf me-2 text-primary"></i>
                                    <span id="fileName">example.pdf</span>
                                    <span class="text-muted ms-2" id="fileSize">(0 KB)</span>
                                </div>
                                <button class="btn btn-sm btn-outline-danger" id="removeFile">
                                    <i class="fas fa-times"></i> 移除
                                </button>
                            </div>
                            <div class="progress mt-2">
                                <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- PDF预览和修改区域 -->
                <div class="card d-none" id="modificationArea">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-edit me-2"></i>PDF内容修改</span>
                        <div class="zoom-controls">
                            <button class="btn btn-sm btn-outline-secondary" id="zoomOut">
                                <i class="fas fa-search-minus"></i>
                            </button>
                            <span class="mx-2 text-muted" id="zoomLevel">100%</span>
                            <button class="btn btn-sm btn-outline-secondary" id="zoomIn">
                                <i class="fas fa-search-plus"></i>
                            </button>
                            <span class="ms-3">适合宽度:</span>
                            <button class="btn btn-sm btn-outline-primary ms-2" id="fitWidth">
                                <i class="fas fa-arrows-alt-h"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <div class="pdf-preview-wrapper" id="pdfPreview">
                                    <div class="pdf-container" id="pdfContainer">
                                        <div class="coordinates-display d-none" id="coordinatesDisplay">
                                            X: 0, Y: 0
                                        </div>
                                        <canvas id="pdfCanvas" class="page-canvas"></canvas>
                                        <div class="selection-area d-none" id="selectionArea"></div>
                                    </div>
                                </div>
                                <div class="page-controls">
                                    <button class="btn btn-outline-primary" id="prevPage">
                                        <i class="fas fa-chevron-left me-1"></i>上一页
                                    </button>
                                    <span>第 <span id="currentPage">1</span> 页，共 <span id="totalPages">1</span> 页</span>
                                    <button class="btn btn-outline-primary" id="nextPage">
                                        下一页 <i class="fas fa-chevron-right ms-1"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" id="clearSelection">
                                        <i class="fas fa-times"></i> 清除选择
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="modification-controls">
                                    <h5>修改操作</h5>
                                    <div class="mb-3">
                                        <label class="form-label">选择修改类型</label>
                                        <select class="form-select" id="modificationType">
                                            <option value="text">文本替换</option>
                                            <option value="image">图片替换</option>
                                            <option value="watermark">添加水印</option>
                                            <option value="annotation">添加注释</option>
                                        </select>
                                    </div>
                                    
                                    <div id="textModification" class="modification-panel">
                                        <div class="mb-3">
                                            <label class="form-label">原文本内容</label>
                                            <textarea class="form-control" rows="3" placeholder="输入要替换的文本内容" id="originalText"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">新文本内容</label>
                                            <textarea class="form-control" rows="3" placeholder="输入替换后的文本内容" id="newText"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">字体</label>
                                            <select class="form-select" id="fontFamily">
                                                <option>宋体</option>
                                                <option>黑体</option>
                                                <option>微软雅黑</option>
                                                <option>Arial</option>
                                            </select>
                                        </div>
                                        <div class="row">
                                            <div class="col-6">
                                                <label class="form-label">字号</label>
                                                <input type="number" class="form-control" id="fontSize" value="12">
                                            </div>
                                            <div class="col-6">
                                                <label class="form-label">颜色</label>
                                                <input type="color" class="form-control" id="fontColor" value="#000000">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div id="imageModification" class="modification-panel d-none">
                                        <div class="mb-3">
                                            <label class="form-label">上传新图片</label>
                                            <input type="file" class="form-control" id="imageUpload" accept="image/*">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">缩放比例</label>
                                            <input type="range" class="form-range" id="imageScale" min="10" max="200" value="100">
                                            <div class="text-end"><span id="scaleValue">100%</span></div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">选择区域坐标</label>
                                        <div class="row">
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectX" placeholder="X坐标" readonly>
                                            </div>
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectY" placeholder="Y坐标" readonly>
                                            </div>
                                        </div>
                                        <div class="row mt-2">
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectWidth" placeholder="宽度" readonly>
                                            </div>
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectHeight" placeholder="高度" readonly>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <button class="btn btn-primary w-100 mt-3" id="addModification">
                                        <i class="fas fa-plus me-1"></i> 添加修改操作
                                    </button>
                                    
                                    <div class="mt-4">
                                        <h6>已添加的修改操作</h6>
                                        <div id="modificationList">
                                            <div class="text-muted text-center py-3">暂无修改操作</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 操作日志 -->
                <div class="card d-none" id="logArea">
                    <div class="card-header">
                        <i class="fas fa-list-alt me-2"></i>操作日志
                    </div>
                    <div class="card-body">
                        <div class="operation-log" id="operationLog">
                            <div class="log-entry">
                                <span class="log-time">09:30:15</span> - 系统就绪，等待上传PDF文件
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-outline-secondary" id="resetButton">
                        <i class="fas fa-redo me-1"></i> 重置
                    </button>
                    <div>
                        <button class="btn btn-outline-primary me-2" id="previewButton" disabled>
                            <i class="fas fa-eye me-1"></i> 预览修改
                        </button>
                        <button class="btn btn-success" id="downloadButton" disabled>
                            <i class="fas fa-download me-1"></i> 下载修改后的PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap & PDF.js -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
    <script>
        // 设置PDF.js worker路径
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';
        
        // 后端API配置
        const API_CONFIG = {
            baseURL: 'http://localhost:8080', // 根据实际后端地址修改
            preview: '/aaa/bbb',  // 预览接口
            download: '/aaa/ccc'  // 下载接口
        };
        
        // 全局变量
        let currentPdf = null;
        let currentPageNum = 1;
        let totalPages = 0;
        let scale = 1.0;
        let modifications = [];
        let isSelecting = false;
        let selectionStart = { x: 0, y: 0 };
        let currentSelection = null;
        let isResizing = false;
        let resizeHandle = null;
        let containerOffset = { x: 0, y: 0 };
        let currentFile = null;
        
        // DOM元素
        const fileInput = document.getElementById('fileInput');
        const uploadButton = document.getElementById('uploadButton');
        const fileUploadArea = document.getElementById('fileUploadArea');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        const removeFile = document.getElementById('removeFile');
        const modificationArea = document.getElementById('modificationArea');
        const pdfCanvas = document.getElementById('pdfCanvas');
        const pdfContainer = document.getElementById('pdfContainer');
        const selectionArea = document.getElementById('selectionArea');
        const currentPageSpan = document.getElementById('currentPage');
        const totalPagesSpan = document.getElementById('totalPages');
        const prevPageButton = document.getElementById('prevPage');
        const nextPageButton = document.getElementById('nextPage');
        const zoomInButton = document.getElementById('zoomIn');
        const zoomOutButton = document.getElementById('zoomOut');
        const fitWidthButton = document.getElementById('fitWidth');
        const zoomLevel = document.getElementById('zoomLevel');
        const modificationType = document.getElementById('modificationType');
        const modificationPanels = document.querySelectorAll('.modification-panel');
        const addModificationButton = document.getElementById('addModification');
        const modificationList = document.getElementById('modificationList');
        const logArea = document.getElementById('logArea');
        const operationLog = document.getElementById('operationLog');
        const previewButton = document.getElementById('previewButton');
        const downloadButton = document.getElementById('downloadButton');
        const resetButton = document.getElementById('resetButton');
        const scaleValue = document.getElementById('scaleValue');
        const scaleSlider = document.getElementById('imageScale');
        const coordinatesDisplay = document.getElementById('coordinatesDisplay');
        const clearSelectionButton = document.getElementById('clearSelection');
        const selectX = document.getElementById('selectX');
        const selectY = document.getElementById('selectY');
        const selectWidth = document.getElementById('selectWidth');
        const selectHeight = document.getElementById('selectHeight');
        const loadingOverlay = document.getElementById('loadingOverlay');
        const loadingText = document.getElementById('loadingText');
        const alertArea = document.getElementById('alertArea');
        const originalText = document.getElementById('originalText');
        const newText = document.getElementById('newText');
        const fontFamily = document.getElementById('fontFamily');
        const fontSize = document.getElementById('fontSize');
        const fontColor = document.getElementById('fontColor');
        const imageUpload = document.getElementById('imageUpload');
        
        // 事件监听器
        uploadButton.addEventListener('click', () => fileInput.click());
        fileInput.addEventListener('change', handleFileSelect);
        fileUploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileUploadArea.classList.add('dragover');
        });
        fileUploadArea.addEventListener('dragleave', () => {
            fileUploadArea.classList.remove('dragover');
        });
        fileUploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            fileUploadArea.classList.remove('dragover');
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                handleFileSelect();
            }
        });
        removeFile.addEventListener('click', resetApp);
        prevPageButton.addEventListener('click', () => changePage(-1));
        nextPageButton.addEventListener('click', () => changePage(1));
        zoomInButton.addEventListener('click', () => changeZoom(0.2));
        zoomOutButton.addEventListener('click', () => changeZoom(-0.2));
        fitWidthButton.addEventListener('click', fitToWidth);
        modificationType.addEventListener('change', showModificationPanel);
        addModificationButton.addEventListener('click', addModification);
        previewButton.addEventListener('click', previewModifications);
        downloadButton.addEventListener('click', downloadModifiedPdf);
        resetButton.addEventListener('click', resetApp);
        scaleSlider.addEventListener('input', (e) => {
            scaleValue.textContent = e.target.value + '%';
        });
        clearSelectionButton.addEventListener('click', clearSelection);
        
        // 初始化事件监听
        pdfContainer.addEventListener('mousedown', startSelection);
        pdfContainer.addEventListener('mousemove', handleMouseMove);
        pdfContainer.addEventListener('mouseup', endSelection);
        pdfContainer.addEventListener('mouseleave', () => {
            coordinatesDisplay.classList.add('d-none');
        });
        
        addLogEntry('系统初始化完成');
        
        // API调用函数
        async function callApi(endpoint, data, isDownload = false) {
            const url = API_CONFIG.baseURL + endpoint;
            
            try {
                showLoading(isDownload ? '生成文件中...' : '处理中...');
                
                const formData = new FormData();
                
                // 添加文件
                if (currentFile) {
                    formData.append('file', currentFile);
                }
                
                // 添加修改数据
                formData.append('modifications', JSON.stringify({
                    modifications: modifications,
                    pageInfo: {
                        currentPage: currentPageNum,
                        totalPages: totalPages,
                        scale: scale
                    }
                }));
                
                // 添加其他表单数据
                for (let key in data) {
                    if (data[key] !== undefined && data[key] !== null) {
                        formData.append(key, data[key]);
                    }
                }
                
                const response = await fetch(url, {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                if (isDownload) {
                    // 处理下载
                    const blob = await response.blob();
                    const downloadUrl = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = downloadUrl;
                    a.download = `modified_${currentFile.name || 'document.pdf'}`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(downloadUrl);
                    
                    showAlert('文件下载成功！', 'success');
                } else {
                    // 处理预览响应
                    const result = await response.json();
                    return result;
                }
            } catch (error) {
                console.error('API调用失败:', error);
                showAlert(`操作失败: ${error.message}`, 'danger');
                throw error;
            } finally {
                hideLoading();
            }
        }
        
        // 工具函数
        function showLoading(text = '处理中...') {
            loadingText.textContent = text;
            loadingOverlay.style.display = 'flex';
        }
        
        function hideLoading() {
            loadingOverlay.style.display = 'none';
        }
        
        function showAlert(message, type = 'info') {
            const alertId = 'alert-' + Date.now();
            const alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" id="${alertId}">
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            alertArea.innerHTML = alertHtml;
            
            // 5秒后自动消失
            setTimeout(() => {
                const alert = document.getElementById(alertId);
                if (alert) {
                    alert.remove();
                }
            }, 5000);
        }
        
        // 修改后的函数
        function handleFileSelect() {
            if (!fileInput.files.length) return;
            
            const file = fileInput.files[0];
            currentFile = file;
            
            if (file.type !== 'application/pdf') {
                alert('请选择PDF文件');
                return;
            }
            
            // 显示文件信息
            fileName.textContent = file.name;
            fileSize.textContent = `(${(file.size / 1024).toFixed(1)} KB)`;
            fileInfo.classList.remove('d-none');
            
            // 模拟上传进度
            const progressBar = fileInfo.querySelector('.progress-bar');
            let progress = 0;
            const interval = setInterval(() => {
                progress += 5;
                progressBar.style.width = `${progress}%`;
                if (progress >= 100) {
                    clearInterval(interval);
                    loadPdf(file);
                }
            }, 100);
            
            addLogEntry(`已上传PDF文件: ${file.name}`);
        }
        
        function addModification() {
            if (!currentSelection || currentSelection.width < 10 || currentSelection.height < 10) {
                showAlert('请先选择一个有效的区域', 'warning');
                return;
            }
            
            const type = modificationType.value;
            const modificationData = {
                type: type,
                page: currentPageNum,
                x: Math.round(currentSelection.x),
                y: Math.round(currentSelection.y),
                width: Math.round(currentSelection.width),
                height: Math.round(currentSelection.height),
                description: `第${currentPageNum}页的${getModificationTypeText(type)}修改`
            };
            
            // 根据类型添加特定数据
            switch (type) {
                case 'text':
                    modificationData.originalText = originalText.value;
                    modificationData.newText = newText.value;
                    modificationData.fontFamily = fontFamily.value;
                    modificationData.fontSize = fontSize.value;
                    modificationData.fontColor = fontColor.value;
                    break;
                case 'image':
                    modificationData.imageScale = scaleSlider.value;
                    // 这里可以处理图片文件上传
                    break;
                case 'watermark':
                    modificationData.watermarkText = newText.value || '水印';
                    break;
                case 'annotation':
                    modificationData.annotationText = newText.value;
                    break;
            }
            
            modifications.push({
                id: Date.now(),
                ...modificationData
            });
            
            updateModificationList();
            addLogEntry(`已添加修改操作: ${modificationData.description}`);
            showAlert('修改操作已添加', 'success');
        }
        
        async function previewModifications() {
            if (modifications.length === 0) {
                showAlert('请先添加修改操作', 'warning');
                return;
            }
            
            try {
                addLogEntry('正在生成预览...');
                showLoading('生成预览中...');
                
                const result = await callApi(API_CONFIG.preview, {
                    action: 'preview',
                    page: currentPageNum
                });
                
                if (result.success) {
                    // 这里可以处理预览结果，比如显示预览图片等
                    addLogEntry('预览生成成功');
                    showAlert('预览生成成功！', 'success');
                    
                    // 模拟预览功能 - 在实际应用中这里会显示预览结果
                    setTimeout(() => {
                        showAlert('预览功能: 在实际应用中这里会显示修改后的预览效果', 'info');
                    }, 1000);
                    
                } else {
                    throw new Error(result.message || '预览生成失败');
                }
            } catch (error) {
                addLogEntry('预览生成失败: ' + error.message);
                showAlert('预览生成失败: ' + error.message, 'danger');
            }
        }
        
        async function downloadModifiedPdf() {
            if (modifications.length === 0) {
                showAlert('请先添加修改操作', 'warning');
                return;
            }
            
            try {
                addLogEntry('开始处理PDF修改...');
                
                await callApi(API_CONFIG.download, {
                    action: 'download',
                    fileName: currentFile.name
                }, true);
                
                addLogEntry('PDF处理完成，开始下载');
                updateStepIndicator(4);
                
            } catch (error) {
                addLogEntry('PDF处理失败: ' + error.message);
                // showAlert已经在callApi中处理
            }
        }
        
        // 其他函数保持不变（renderPage, changePage, changeZoom, fitToWidth, startSelection, handleMouseMove等）
        // 这里省略了其他未修改的函数以保持代码简洁，实际使用时需要保留
        
        function renderPage(pageNum) {
            if (!currentPdf) return;
            
            currentPdf.getPage(pageNum).then(page => {
                const viewport = page.getViewport({ scale: scale });
                
                // 调整canvas大小
                const canvasContext = pdfCanvas.getContext('2d');
                pdfCanvas.height = viewport.height;
                pdfCanvas.width = viewport.width;
                
                // 计算容器偏移量（用于准确定位）
                const containerRect = pdfContainer.getBoundingClientRect();
                containerOffset.x = containerRect.left;
                containerOffset.y = containerRect.top;
                
                // 渲染PDF页面
                const renderContext = {
                    canvasContext: canvasContext,
                    viewport: viewport
                };
                
                page.render(renderContext).promise.then(() => {
                    currentPageSpan.textContent = pageNum;
                    addLogEntry('已渲染第' + pageNum + '页');
                    
                    // 重新显示当前选择区域（如果有）
                    if (currentSelection) {
                        updateSelectionArea();
                    }
                });
            });
        }
        
        function changePage(direction) {
            const newPageNum = currentPageNum + direction;
            if (newPageNum < 1 || newPageNum > totalPages) return;
            
            currentPageNum = newPageNum;
            renderPage(currentPageNum);
            clearSelection();
        }
        
        function changeZoom(delta) {
            scale += delta;
            if (scale < 0.2) scale = 0.2;
            if (scale > 3) scale = 3;
            
            zoomLevel.textContent = Math.round(scale * 100) + '%';
            renderPage(currentPageNum);
        }
        
        function fitToWidth() {
            if (!currentPdf) return;
            
            currentPdf.getPage(currentPageNum).then(page => {
                const viewport = page.getViewport({ scale: 1 });
                const containerWidth = pdfContainer.clientWidth - 40;
                scale = containerWidth / viewport.width;
                
                zoomLevel.textContent = Math.round(scale * 100) + '%';
                renderPage(currentPageNum);
                addLogEntry('已调整到适合宽度显示');
            });
        }
        
        function startSelection(e) {
            const containerRect = pdfContainer.getBoundingClientRect();
            containerOffset.x = containerRect.left;
            containerOffset.y = containerRect.top;
            
            const x = e.clientX - containerOffset.x;
            const y = e.clientY - containerOffset.y;
            
            if (x < 0 || y < 0 || x > pdfCanvas.width || y > pdfCanvas.height) {
                return;
            }
            
            if (currentSelection && isResizingHandle(x, y)) {
                isResizing = true;
                return;
            }
            
            isSelecting = true;
            selectionStart = { x, y };
            
            currentSelection = {
                x: x,
                y: y,
                width: 0,
                height: 0
            };
            
            updateSelectionArea();
            selectionArea.classList.remove('d-none');
        }
        
        function handleMouseMove(e) {
            const containerRect = pdfContainer.getBoundingClientRect();
            containerOffset.x = containerRect.left;
            containerOffset.y = containerRect.top;
            
            const x = e.clientX - containerOffset.x;
            const y = e.clientY - containerOffset.y;
            
            if (x >= 0 && y >= 0 && x <= pdfCanvas.width && y <= pdfCanvas.height) {
                coordinatesDisplay.textContent = `X: ${Math.round(x)}, Y: ${Math.round(y)}`;
                coordinatesDisplay.classList.remove('d-none');
                coordinatesDisplay.style.left = (x + 10) + 'px';
                coordinatesDisplay.style.top = (y - 30) + 'px';
            } else {
                coordinatesDisplay.classList.add('d-none');
            }
            
            if (isResizing) {
                handleResize(x, y);
            } else if (isSelecting) {
                currentSelection.width = x - selectionStart.x;
                currentSelection.height = y - selectionStart.y;
                
                if (currentSelection.width < 0) {
                    currentSelection.x = x;
                    currentSelection.width = -currentSelection.width;
                }
                if (currentSelection.height < 0) {
                    currentSelection.y = y;
                    currentSelection.height = -currentSelection.height;
                }
                
                if (currentSelection.x < 0) currentSelection.x = 0;
                if (currentSelection.y < 0) currentSelection.y = 0;
                if (currentSelection.x + currentSelection.width > pdfCanvas.width) {
                    currentSelection.width = pdfCanvas.width - currentSelection.x;
                }
                if (currentSelection.y + currentSelection.height > pdfCanvas.height) {
                    currentSelection.height = pdfCanvas.height - currentSelection.y;
                }
                
                updateSelectionArea();
                updateCoordinateInputs();
            }
        }
        
        function resetApp() {
            currentPdf = null;
            currentPageNum = 1;
            totalPages = 0;
            scale = 1.0;
            modifications = [];
            currentSelection = null;
            currentFile = null;
            
            fileInput.value = '';
            fileInfo.classList.add('d-none');
            modificationArea.classList.add('d-none');
            logArea.classList.add('d-none');
            selectionArea.classList.add('d-none');
            modificationList.innerHTML = '<div class="text-muted text-center py-3">暂无修改操作</div>';
            previewButton.disabled = true;
            downloadButton.disabled = true;
            
            // 清空表单
            originalText.value = '';
            newText.value = '';
            fontFamily.value = '宋体';
            fontSize.value = '12';
            fontColor.value = '#000000';
            
            updateStepIndicator(1);
            addLogEntry('系统已重置，等待上传新的PDF文件');
            showAlert('系统已重置', 'info');
        }
        
        // 其他辅助函数保持不变...
        function endSelection() {
            isSelecting = false;
            isResizing = false;
            
            if (currentSelection && (currentSelection.width > 5 || currentSelection.height > 5)) {
                addLogEntry(`已在第${currentPageNum}页选择区域: X=${Math.round(currentSelection.x)}, Y=${Math.round(currentSelection.y)}, 宽度=${Math.round(currentSelection.width)}, 高度=${Math.round(currentSelection.height)}`);
            }
        }
        
        function updateSelectionArea() {
            if (!currentSelection) return;
            
            selectionArea.style.left = currentSelection.x + 'px';
            selectionArea.style.top = currentSelection.y + 'px';
            selectionArea.style.width = currentSelection.width + 'px';
            selectionArea.style.height = currentSelection.height + 'px';
            
            addResizeHandles();
        }
        
        function addResizeHandles() {
            document.querySelectorAll('.selection-handle').forEach(handle => handle.remove());
            
            if (!currentSelection || currentSelection.width < 20 || currentSelection.height < 20) return;
            
            const handles = [
                { class: 'nw', left: 0, top: 0 },
                { class: 'n', left: '50%', top: 0 },
                { class: 'ne', left: '100%', top: 0 },
                { class: 'w', left: 0, top: '50%' },
                { class: 'e', left: '100%', top: '50%' },
                { class: 'sw', left: 0, top: '100%' },
                { class: 's', left: '50%', top: '100%' },
                { class: 'se', left: '100%', top: '100%' }
            ];
            
            handles.forEach(handle => {
                const handleEl = document.createElement('div');
                handleEl.className = `selection-handle ${handle.class}`;
                handleEl.style.left = handle.left;
                handleEl.style.top = handle.top;
                selectionArea.appendChild(handleEl);
            });
        }
        
        function isResizingHandle(x, y) {
            const handles = document.querySelectorAll('.selection-handle');
            for (let handle of handles) {
                const handleRect = handle.getBoundingClientRect();
                if (x >= handleRect.left - containerOffset.x && x <= handleRect.right - containerOffset.x && 
                    y >= handleRect.top - containerOffset.y && y <= handleRect.bottom - containerOffset.y) {
                    resizeHandle = handle.className.split(' ')[1];
                    return true;
                }
            }
            return false;
        }
        
        function handleResize(x, y) {
            if (!currentSelection || !resizeHandle) return;
            
            switch (resizeHandle) {
                case 'nw':
                    currentSelection.width += currentSelection.x - x;
                    currentSelection.height += currentSelection.y - y;
                    currentSelection.x = x;
                    currentSelection.y = y;
                    break;
                case 'n':
                    currentSelection.height += currentSelection.y - y;
                    currentSelection.y = y;
                    break;
                case 'ne':
                    currentSelection.width = x - currentSelection.x;
                    currentSelection.height += currentSelection.y - y;
                    currentSelection.y = y;
                    break;
                case 'w':
                    currentSelection.width += currentSelection.x - x;
                    currentSelection.x = x;
                    break;
                case 'e':
                    currentSelection.width = x - currentSelection.x;
                    break;
                case 'sw':
                    currentSelection.width += currentSelection.x - x;
                    currentSelection.height = y - currentSelection.y;
                    currentSelection.x = x;
                    break;
                case 's':
                    currentSelection.height = y - currentSelection.y;
                    break;
                case 'se':
                    currentSelection.width = x - currentSelection.x;
                    currentSelection.height = y - currentSelection.y;
                    break;
            }
            
            if (currentSelection.width < 10) currentSelection.width = 10;
            if (currentSelection.height < 10) currentSelection.height = 10;
            if (currentSelection.x < 0) currentSelection.x = 0;
            if (currentSelection.y < 0) currentSelection.y = 0;
            if (currentSelection.x + currentSelection.width > pdfCanvas.width) {
                currentSelection.width = pdfCanvas.width - currentSelection.x;
            }
            if (currentSelection.y + currentSelection.height > pdfCanvas.height) {
                currentSelection.height = pdfCanvas.height - currentSelection.y;
            }
            
            updateSelectionArea();
            updateCoordinateInputs();
        }
        
        function updateCoordinateInputs() {
            if (!currentSelection) return;
            
            selectX.value = Math.round(currentSelection.x);
            selectY.value = Math.round(currentSelection.y);
            selectWidth.value = Math.round(currentSelection.width);
            selectHeight.value = Math.round(currentSelection.height);
        }
        
        function clearSelection() {
            currentSelection = null;
            selectionArea.classList.add('d-none');
            document.querySelectorAll('.selection-handle').forEach(handle => handle.remove());
            
            selectX.value = '';
            selectY.value = '';
            selectWidth.value = '';
            selectHeight.value = '';
            
            addLogEntry('已清除选择区域');
        }
        
        function showModificationPanel() {
            const type = modificationType.value;
            modificationPanels.forEach(panel => panel.classList.add('d-none'));
            document.getElementById(type + 'Modification').classList.remove('d-none');
        }
        
        function getModificationTypeText(type) {
            const types = {
                'text': '文本替换',
                'image': '图片替换',
                'watermark': '添加水印',
                'annotation': '添加注释'
            };
            return types[type] || '未知';
        }
        
        function updateModificationList() {
            if (modifications.length === 0) {
                modificationList.innerHTML = '<div class="text-muted text-center py-3">暂无修改操作</div>';
                return;
            }
            
            modificationList.innerHTML = '';
            modifications.forEach(mod => {
                const item = document.createElement('div');
                item.className = 'modification-item';
                item.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <strong>${getModificationTypeText(mod.type)}</strong>
                            <div class="small text-muted">${mod.description}</div>
                            <div class="small">位置: (${mod.x}, ${mod.y}) 大小: ${mod.width}×${mod.height}</div>
                        </div>
                        <button class="btn btn-sm btn-outline-danger remove-modification" data-id="${mod.id}">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                `;
                modificationList.appendChild(item);
            });
            
            document.querySelectorAll('.remove-modification').forEach(button => {
                button.addEventListener('click', function() {
                    const id = parseInt(this.getAttribute('data-id'));
                    removeModification(id);
                });
            });
        }
        
        function removeModification(id) {
            modifications = modifications.filter(mod => mod.id !== id);
            updateModificationList();
            addLogEntry('已删除修改操作 ID: ' + id);
            showAlert('修改操作已删除', 'info');
        }
        
        function updateStepIndicator(step) {
            document.querySelectorAll('.step').forEach((s, index) => {
                s.classList.remove('active', 'completed');
                if (index + 1 < step) {
                    s.classList.add('completed');
                } else if (index + 1 === step) {
                    s.classList.add('active');
                }
            });
        }
        
        function addLogEntry(message) {
            const now = new Date();
            const timeString = now.getHours().toString().padStart(2, '0') + ':' + 
                              now.getMinutes().toString().padStart(2, '0') + ':' + 
                              now.getSeconds().toString().padStart(2, '0');
            
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = `<span class="log-time">${timeString}</span> - ${message}`;
            
            operationLog.appendChild(logEntry);
            operationLog.scrollTop = operationLog.scrollHeight;
        }
        
        function loadPdf(file) {
            const fileReader = new FileReader();
            
            fileReader.onload = function() {
                const typedarray = new Uint8Array(this.result);
                
                pdfjsLib.getDocument(typedarray).promise.then(pdf => {
                    currentPdf = pdf;
                    totalPages = pdf.numPages;
                    totalPagesSpan.textContent = totalPages;
                    currentPageNum = 1;
                    
                    modificationArea.classList.remove('d-none');
                    logArea.classList.remove('d-none');
                    
                    updateStepIndicator(2);
                    renderPage(currentPageNum);
                    
                    addLogEntry('PDF文件加载成功，共' + totalPages + '页');
                    previewButton.disabled = false;
                    downloadButton.disabled = false;
                }).catch(error => {
                    console.error('Error loading PDF:', error);
                    addLogEntry('PDF文件加载失败: ' + error.message);
                    showAlert('PDF文件加载失败', 'danger');
                });
            };
            
            fileReader.readAsArrayBuffer(file);
        }
    </script>
</body>
</html>